package com.aispeech.asr.webase.config.error;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ResponseStatusException;

import java.util.LinkedHashMap;
import java.util.Map;

@Component
@Slf4j
public class GlobalErrorAttributes extends DefaultErrorAttributes {
    public GlobalErrorAttributes() {
        super(false);
    }

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = new LinkedHashMap<>();
        Throwable error = getError(request);

        if (error instanceof ResponseStatusException) {
            ResponseStatusException exception = (ResponseStatusException) error;
            errorAttributes.put("code", exception.getStatus().value());
            errorAttributes.put("message", String.format("path: %s, error: %s",
                    request.path(), exception.getReason()));

        } else {
            errorAttributes = super.getErrorAttributes(request, includeStackTrace);
            errorAttributes.put("code", errorAttributes.getOrDefault("status", HttpStatus.BAD_REQUEST));
            errorAttributes.put("message", String.format("path: %s, error: %s", request.path(), error.getMessage()));
        }

        log.warn("path: {}, error: {}, from: {}, cause by: {}",
                request.path(),
                error.getMessage(),
                request.remoteAddress().get(),
                error.getStackTrace()[0]);

        return errorAttributes;
    }

}
